<template>
	<diyNavVue :title="toInfo.name"></diyNavVue>
	<view class="page-content">
		<view :class="['message-item', item.fromId===meId?'right' : '']" v-for="item in messageList">
			<image v-if="item.fromId!==meId" class="avatar-img" :src="toInfo.avatar"></image>
			<view v-if="typeof item.message === 'string'" class="message-text">
				<rich-text :nodes="item.message"></rich-text>
			</view>
			<up-icon v-else @click="playAudio(item)" name="volume" size="30"></up-icon>
			<image v-if="item.fromId===meId" class="avatar-img" :src="myInfo.avatar"></image>
		</view>
	</view>
	<view class="footer">
		<view class="btn">
			<up-icon @click="handleIcon" name="chat-fill" size="40"></up-icon>
			<view class="send-model">
				<up-input size="mini" placeholder="请输入内容" border="surround" v-model="message"></up-input>
				<button size="mini" @click="doSend">发送</button>
			</view>
			<up-icon @click="handleImage" name="photo" size="40"></up-icon>
			<up-icon @longpress="startRecorder" @touchend="stopRecorder" name="mic" size="40"></up-icon>
		</view>
		<view v-if="showIcon" class="icon-list">
			<image @click="selectIcon(item)" class="icon-item" :src="item.iconUrl" mode="" v-for="item in iconList"></image>
		</view>
		
	</view>

</template>

<script setup>
	import io from '@hyoga/uni-socket.io';
	import {
		ref
	} from 'vue';
	import diyNavVue from '../../components/diy-nav/diy-nav.vue';
	import {
		onLoad
	} from '@dcloudio/uni-app'
	const personObj = uniCloud.importObject('person')
	// #ifdef MP-WEIXIN
	
	// 生成全局唯一的录音管理器
	const recorderManager = uni.getRecorderManager()
	// 生成语音播放的对象实例
	const audio = uni.createInnerAudioContext()
	recorderManager.onStop((res) => {
		console.log(res)
		const messageObj = {
			fromId: meId.value,
			toId: toId.value,
			message: {
				type: 'audio',
				url: res.tempFilePath
			}
		}
		messageList.value.push(messageObj)
		socket.emit('sendMsg', messageObj)
	})
	// #endif
	const playAudio = (messageObj) => {
		const url = messageObj.message.url
		audio.src = url
		if(audio.paused) {
			audio.play()
		} else {
			audio.pause()
		}
	}
	const title = ref('对方的名字')
	const meId = ref('')
	const toId = ref('')
	const myInfo = ref({})
	const toInfo = ref({})
	const message = ref('')
	// 定义控制表情列表展示与否的变量
	const showIcon = ref(false)
	// 定义表情包图片以及标识的数据
	const iconList = ref([
		{iconUrl: '/static/icon/bs.png', code: '/bs'},
		{iconUrl: '/static/icon/cj.png', code: '/cj'},
		{iconUrl: '/static/icon/eye.png', code: '/eye'},
		{iconUrl: '/static/icon/sq.png', code: '/sq'},
		{iconUrl: '/static/icon/yg.png', code: '/yg'}
	])
	const handleIcon = () => {
		showIcon.value = !showIcon.value
	}
	const handleImage = () => {
		// 选择图片的API
		uni.chooseImage({
			success(res) {
				console.log(res)
				// 正常逻辑：选择完图片，进行上传，上传完成拿到url
				setTimeout(() => {
					// 模拟图片上传完成
					const url = res.tempFilePaths[0]
					const messageObj = {
						fromId: meId.value,
						toId: toId.value,
						message: `<img src="${url}" width="100px" >`
					}
					messageList.value.push(messageObj)
					socket.emit('sendMsg', messageObj)
				}, 2000)
			}
		})
	}
	// 长按开始录音
	const startRecorder = () => {
		console.log('开始录音')
		recorderManager.start()
	}
	// 松开结束录音
	const stopRecorder = () => {
		console.log('结束录音')
		recorderManager.stop()
	}
	// 选择某一个表情的方法
	const selectIcon = (iconItem) => {
		console.log(iconItem)
		message.value += iconItem.code
	}
	// 模拟数据库里面的数据
	const personList = [{
			id: 'bin',
			name: '李少斌',
			avatar: 'http://gips0.baidu.com/it/u=3560029307,576412274&fm=3028&app=3028&f=JPEG&fmt=auto?w=960&h=1280'
		},
		{
			id: 'zxy',
			name: '李学友',
			avatar: 'https://img2.baidu.com/it/u=1076721627,2837344772&fm=253&fmt=auto&app=138&f=JPEG?w=665&h=948'
		},
		{
			id: 'ldh',
			name: '刘德华',
			avatar: 'https://img1.baidu.com/it/u=3881792890,1651954867&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1098'
		}
	]
	const getUserInfo = async () => {
		myInfo.value = personList.find(item => item.id === meId.value) || {}
		// toInfo.value = personList.find(item => item.id === toId.value) || {}
		const personDetail = await personObj.getPersonDetail(toId.value)
		if(personDetail.data.length>0) {
			toInfo.value = personDetail.data[0]
		}
	}
	// 定义存储定时器的变量
	let timer
	const doHeart = () => {
		// 重置定时器
		// 如果已经有定时器，那么先清除再设置
		timer && clearInterval(timer)
		
		timer = setInterval(() => {
			socket.emit('ping')
		}, 20000)
	}
	
	let socket = null
	const linkSocket = () => {
		// 链接服务端
		socket = io('ws://localhost:3000', {
			path: '/mysocket',
			query: {
				id: meId.value
			},
			transports: ['websocket', 'polling'],
			timeout: 5000,
		});
		// 客户端监听连接服务成功的事件
		socket.on('connect', () => {
			console.log('连接服务端成功')
			// 开始心跳检测
			doHeart()
			// 注册接收消息的信号
			socket.on('receiveMsg', info => {
				messageList.value.push(info)
				uni.setStorageSync('messageList', messageList.value)
			})
			// 注册接收心跳检测信号结果的事件
			socket.on('pang', () => {
				console.log('一次心跳检测完成')
			})
		});
	}
	onLoad((options) => {
		meId.value = options.meId
		toId.value = options.toId
		getUserInfo()
		linkSocket()
	})
	const messageList = ref([])
	const messageHistory = uni.getStorageSync('messageList')
	messageList.value = messageHistory || []
	
	
	// 定义方法检查字符串是否包含某一个表情的code，如果包含替换字符串
	const codeToImgStr = (str) => {
		// 'abcd/bs'
		let newStr = str
		// newStr = 'abcd/bs'
		// 检查匹配表情code 
		iconList.value.forEach(item => {
			// item = {iconUrl: '/static/icon/bs.png', code: '/bs'}
			newStr = newStr.replaceAll(item.code, `<img style="width： 50px;height:50px;" src="${item.iconUrl}" />`)
			//abcd<img style="width： 50px;height:50px;" src="/static/icon/bs.png" />
		})
		
		return newStr
	}
	const doSend = () => {
		console.log(message.value)
		// 发送表情的时候，构造聊天对象中消息内容的时候，要检查消息内容是否包含了某一个表情的code
		// 如果匹配到了某一个表情，把对应的code替换成一个图片标签并且把src放在上面
		// 举例：message.value = /bs => 把/bs替换成'<img src="/static/icon/bs.png" />'
		const messageObj = {
			fromId: meId.value,
			toId: toId.value,
			message: codeToImgStr(message.value)
		}
		messageList.value.push(messageObj)
		// 触发服务端注册的信号
		socket.emit('sendMsg', messageObj)
		message.value = ''
		uni.setStorageSync('messageList', messageList.value)
	}
</script>

<style lang="scss" scoped>
	.page-content {
		padding-top: 160rpx;
	}

	.avatar-img {
		width: 50rpx;
		height: 50rpx;
	}

	.message-item {
		display: flex;
		align-items: flex-start;

		&.right {
			justify-content: flex-end;
		}
		.message-text{
			display: flex;
			align-items: center;
		}
	}

	.footer {
		position: fixed;
		bottom: 0;
		width: 100vw;
		padding: 20rpx;
		// 怪异(IE)盒模型
		box-sizing: border-box;
		.btn{
			display: flex;
		}
		.send-model {
			display: flex;
		}
		.icon-list{
			margin-top: 20rpx;
		}
		.icon-item{
			width: 50rpx;
			height: 50rpx;
		}
	}
</style>